/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package validator;

import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import utility.ResourceBundleLoader;

/**
 *
 * @author Carmela
 */
@FacesValidator(value="emailValidator")
public class EmailValidator implements Validator{
    
    public static final String emailRegex="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
		+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    public static final String resourceMessageValidation="emailRegexValidatorM";
    public static final String resourceMessage="emailValidatorM";
    
    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if(value != null){
            if(value instanceof String){
                String email=(String)value;
                ResourceBundle rb=ResourceBundleLoader.getResourceBundle(context);
                    if(email.length()<6){
                    FacesMessage fm=new FacesMessage();
                    fm.setSummary(rb.getString(resourceMessage));
                    fm.setSeverity(FacesMessage.SEVERITY_ERROR);
                    throw new ValidatorException(fm);
                }
                if(!email.matches(emailRegex)){
                    FacesMessage fm=new FacesMessage();
                    fm.setSummary(rb.getString(resourceMessageValidation));
                    fm.setSeverity(FacesMessage.SEVERITY_ERROR);
                    throw new ValidatorException(fm);
                }
            }
        }
    }
    
}
